﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Media;
using System.Windows.Media.Animation;
using PairingMatrix.ViewModel;

namespace PairingMatrix.View.Behavior
{
    public class MoveAnimationForTeamMemberCardBehavior : Behavior<TeamMemberCardControl>
    {
        private ContentPresenter _parent;
        private TeamMemberCardViewModel _teamMemberCardViewModel;
        private Storyboard _storyboardMove;
        private DoubleAnimation _xAnimation;
        private DoubleAnimation _yAnimation;
        
        protected override void OnAttached()
        {
            AssociatedObject.Loaded += (sender, e) =>
            {
                _teamMemberCardViewModel = (TeamMemberCardViewModel)AssociatedObject.DataContext;
                _teamMemberCardViewModel.PropertyChanged += TeamMemberCardPropertyChanged;

                if (_parent == null)
                {
                    _parent = (ContentPresenter)VisualTreeHelper.GetParent(AssociatedObject);
                }

                var duration = new Duration(TimeSpan.FromMilliseconds(400));
                _xAnimation = new DoubleAnimation();
                _yAnimation = new DoubleAnimation();

                _xAnimation.Duration = duration;
                _yAnimation.Duration = duration;


                _storyboardMove = new Storyboard();
                _storyboardMove.Duration = duration;

                _storyboardMove.Children.Add(_xAnimation);
                _storyboardMove.Children.Add(_yAnimation);

                Storyboard.SetTarget(_xAnimation, _parent);
                Storyboard.SetTarget(_yAnimation, _parent);

                Storyboard.SetTargetProperty(_xAnimation, new PropertyPath("(Canvas.Left)"));
                Storyboard.SetTargetProperty(_yAnimation, new PropertyPath("(Canvas.Top)"));

        
                MoveCard();
           
            };

        }

        void TeamMemberCardPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "HasSignUpsOnCurrentWall")
            {
                MoveCard();
            }
        }

        private void MoveCard()
        {
            if (_teamMemberCardViewModel.HasSignUpsOnCurrentWall)
            {
                _xAnimation.To = _teamMemberCardViewModel.Position.X;
                _yAnimation.To = _teamMemberCardViewModel.Position.Y;
                _storyboardMove.Begin();
            }
            else
            {
                _xAnimation.To = 200 + 100 * _teamMemberCardViewModel.Order;
                _yAnimation.To = 0;
                _storyboardMove.Begin();
            }
        }
    }
}
